package com.ay.weixin.fdc.front.usercenter.event;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.httpclient.HttpException;
import org.lizar.config.group.Group;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.controller.loader.FilePostForm;
import org.lizar.ioc.Container;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.AppConfig;
import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.FDCProjectStatus;
import com.ay.weixin.config.types.UserStatus;
import com.ay.weixin.config.types.UserType;
import com.ay.weixin.fdc.admin.category.domain.CategoryLoader;
import com.ay.weixin.fdc.boss.autoreply.event.ReplySetting;
import com.ay.weixin.fdc.boss.kanfang.db.IbatisKanFangDao;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectDao;
import com.ay.weixin.fdc.boss.project.domain.FDCProject;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.db.UserDao;
import com.ay.weixin.fdc.boss.user.db.WeiXinInfoDao;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashFlow;
import com.ay.weixin.fdc.front.usercenter.event.manager.Register;

public class UserEvent extends Event implements Before {
	private IbatisProjectDao			project_dao;
	private CategoryLoader				cl;
	private IbatisCashFlow				cash_dao;
	private UserDao						user_dao;
	private FDCAgentDao					fdc_user_dao;
	private IbatisKanFangDao			kanfang_dao;
	private WeiXinInfoDao				weixin_dao;
	
	
	@Override
	public void init_property() throws Exception {
		project_dao = Container.get(IbatisProjectDao.class);
		user_dao = Container.get(UserDao.class);
		cash_dao = Container.get(IbatisCashFlow.class);
		kanfang_dao = Container.get(IbatisKanFangDao.class);
		weixin_dao = Container.get(WeiXinInfoDao.class);
		fdc_user_dao = Container.get(FDCAgentDao.class);
		cl = Container.get(CategoryLoader.class);
	
	
	}
	

	
	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		long wxproject_id=bl.queryPathInt(2);
		bl.setAttr("need_upload_business_card", ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_upload_business_card"));
		bl.setAttr("need_upload_ID_card",ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_upload_ID_card"));
		bl.setAttr("need_invate_code", ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_invate_code"));
	}
	
	public static void setSessionTimeOut(EventLoader el) {
		el.getSession().setMaxInactiveInterval(Keys.getInt("usercenter.session_timeout"));
	}
	
	@Override
	public String default_handling_path() {
		return "/fdc/usercenter/*";
	}
	
	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long wxproject_id=el.queryPathInt(2);
		
		if (el.queryPathCheck(3, "test")) {
			test(el,wxproject_id);
			return;
		}
		if (!el.getBool("is_weixin") && ProjectConfig._bool(wxproject_id,"sys.weixin_only")) {
			el.text("invalid visit");
			return;
		}
		UserBasic user = el.getSessionAttr("user", UserBasic.class);
		if (user == null) {
			el.response_to_root("/fdc/login/"+wxproject_id);
			return;
		}
		if (StringHelper.equals(user.getType(), UserType.manager.name()) || StringHelper.equals(user.getType(), UserType.old.name())
			||StringHelper.equals(user.getType(), UserType.salesman.name())) {
			if (el.queryPathCheck(3, "")) {
				user_center(el,wxproject_id);
			} else if (el.queryPathCheck(3, "profile")) {
				view_profile(el,wxproject_id);
			} else if (el.queryPathCheck(3, "update_profile")) {
				update_profile(el,wxproject_id);
			}
		} else {
			el.response_to_root(Keys.getStr("forward.not_fdc_user")+wxproject_id);
		}
	}
	
	private void test(EventLoader el,long project_id) throws IOException, ServletException {
		
		el.setAttr("location_list", cl.get("location"));
		el.template("/WEB-INF/template/app/"+project_id+"/fdc/usercenter/test.vm");
	}
	
	private void update_profile(EventLoader el,long wxproject_id) throws IOException, ServletException {
		if (!el.isMultipartContent()) {
			el.text("invalid visit.");
			return;
		}
		FDCAgent user = el.getSessionAttr("user", FDCAgent.class);
		UserEvent.inc_vcode_check(el,wxproject_id);
		FilePostForm file = el.parseFilePostForm(Group.getLong("sys.max_image_file_size") * 1024);
		file.setAllParamToAttr(el);
		String vcode = file.getStr("vcode");
		String house = file.getStr("house");
		String msg = null;
		if (file.getErrorMsg() != null) {
			msg = file.getErrorMsg();
			el.setAttr("msg", msg);
			view_profile(el,wxproject_id);
			return;
		}
		
		FileItem business_card = null;
		FileItem ID_card = null;
		List<FileItem> items = file.getFileItems();
		for (FileItem it : items) {
			if (it.getFieldName().toLowerCase().equals("business_card")) {
				business_card = it;
			} else if (it.getFieldName().toLowerCase().equals("id_card")) {
				ID_card = it;
			}
		}
		
		boolean need_vcode = el.getSessionAttr("tel_vcode", 0) >= ProjectConfig.getInt(wxproject_id,"fdc_usercenter.vcode_used_error_in_times");
		if (need_vcode && el.getSessionAttr("vcode") != null && !StringHelper.equals(vcode.toLowerCase(), el.getSessionAttr("vcode").toString().toLowerCase())) {
			msg = el.i18("login.vcode_invalid");
			el.setAttr("msg", msg);
			view_profile(el,wxproject_id);
			return;
		}
		
		if (StringHelper.isNull(house) && StringHelper.equals(user.getType(), "old")) {
			msg = el.i18("fdc_usercenter.house.cannotbe.empty");
			el.setAttr("msg", msg);
			view_profile(el,wxproject_id);
			return;
		}
		
		File business_card_file = null;
		File ID_card_file = null;
		String business_card_file_name = null;
		String ID_card_file_name = null;
		
		if (ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_verify_manually")) {
			user.setProfile_verify(UserBasic.PROFILE.NOT_VERIFY.getValue());
			user.setStatus(UserStatus.apply.name());
		} else {
			user.setProfile_verify(UserBasic.PROFILE.VERIFIED.getValue());
			user.setStatus(UserStatus.ok.name());
		}
		
		if (business_card != null) {
			if (AppConfig.img_support_fix.get(StringHelper.postfix(business_card.getName().toLowerCase())) == null) {
				msg = String.format(el.i18("fdc_usercenter.need_upload_business_card"), Keys.getStr("fdc_usercenter.image_post_fix_support"));
				el.setAttr("msg", msg);
				view_profile(el,wxproject_id);
				return;
			} else {
				business_card_file_name = UUID.randomUUID().toString() + ".jpg";
				String file_path = ReplySetting.getImagePath(el,wxproject_id, business_card_file_name);
				business_card_file = new File(file_path);
				if (!business_card_file.getParentFile().exists()) {
					business_card_file.getParentFile().mkdirs();
				}
				try {
					business_card.write(business_card_file);
				} catch (Exception e) {
					e.printStackTrace();
					msg = el.i18("fdc_usercenter.image.save.failed");
					el.setAttr("msg", msg);
					view_profile(el,wxproject_id);
					return;
				}
			}
		} else {
			if (StringHelper.isNull(user.getBusiness_card_url()) && StringHelper.equals(user.getType(), "manager")) {
				msg = String.format(el.i18("fdc_usercenter.need_upload_business_card"), Keys.getStr("fdc_usercenter.image_post_fix_support"));
				el.setAttr("msg", msg);
				view_profile(el,wxproject_id);
				return;
			}
			
		}
		if (ID_card != null) {
			if (AppConfig.img_support_fix.get(StringHelper.postfix(ID_card.getName().toLowerCase())) == null) {
				msg = String.format(el.i18("fdc_usercenter.need_upload_ID_card"), Keys.getStr("fdc_usercenter.image_post_fix_support"));
				el.setAttr("msg", msg);
				view_profile(el,wxproject_id);
				return;
			} else {
				ID_card_file_name = UUID.randomUUID().toString() + ".jpg";
				String file_path = ReplySetting.getImagePath(el,wxproject_id, ID_card_file_name);
				ID_card_file = new File(file_path);
				try {
					ID_card.write(ID_card_file);
				} catch (Exception e) {
					e.printStackTrace();
					msg = el.i18("fdc_usercenter.image.save.failed");
					el.setAttr("msg", msg);
					view_profile(el,wxproject_id);
					return;
				}
			}
		} else {
			if (StringHelper.isNull(user.getID_card_url()) && StringHelper.equals(user.getType(), "manager")) {
				msg = String.format(el.i18("fdc_usercenter.register_forced_ID_card"), Keys.getStr("fdc_usercenter.image_post_fix_support"));
				el.setAttr("msg", msg);
				view_profile(el,wxproject_id);
				return;
			}
		}
		
		if (business_card != null)
			user.setBusiness_card_url(ReplySetting.getRelatImagePath(el,wxproject_id, business_card_file_name));
		if (ID_card != null)
			user.setID_card_url(ReplySetting.getRelatImagePath(el,wxproject_id, ID_card_file_name));
		if (house != null)
			user.setHouse(house);
		try {
			
			fdc_user_dao.updateProfile(user);
		} catch (Exception e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_usercenter.server_error"));
			
			if (ID_card_file != null) {
				ID_card_file.delete();
			}
			
			if (business_card_file != null) {
				business_card_file.delete();
			}
			
			view_profile(el,wxproject_id);
			return;
		}
		
		el.setAttr("msg", el.i18("user.profile.submit.success"));
		el.setSessionAttr("user", user);
		
		UserWeiXinInfo weixin_info = el.getSessionAttr("weixin_info", UserWeiXinInfo.class);
		if (weixin_info != null) {
			if (ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_verify_manually")) {
				Register.reply(wxproject_id,"资料提交成功", "，您现在可以推荐客户啦", weixin_info.getId(), user);
			} else {
				Register.reply(wxproject_id,"资料提交成功", "，请等待我们的工作人员为您审核", weixin_info.getId(), user);
			}
		}
		
		UserEvent.clean_vcode(el);
		view_profile(el,wxproject_id);
	}
	
	private void view_profile(EventLoader el,long wxproject_id) throws IOException, ServletException {
		UserEvent.load_vcode_check(el,wxproject_id);
		el.setAttr("profile_values", UserBasic.PROFILE.values());
		el.template("/WEB-INF/template/app/"+wxproject_id+"/fdc/usercenter/myinfo.vm");
	}
	
	public static void clean_vcode(EventLoader el) {
		el.removeSessionAttr("tel_vcode");
	}
	
	/**
	 * 
	 * 
	 * 
	 * */
	public static void inc_vcode_check(EventLoader el,long wxproject_id) {
		int vcode = 0;
		if (el.getSessionAttr("tel_vcode") != null) {
			vcode = el.getSessionAttr("tel_vcode", 0) + 1;
		}
		el.setSessionAttr("tel_vcode", vcode);
		if (vcode >= ProjectConfig.getInt(wxproject_id,"fdc_usercenter.vcode_used_error_in_times") - 1) {
			el.setAttr("enable_vcode", true);
		}
	}
	
	public static void load_vcode_check(EventLoader el,long wxproject_id) {
		int vcode = el.getSessionAttr("tel_vcode", 0);
		if (vcode >= ProjectConfig.getInt(wxproject_id,"fdc_usercenter.vcode_used_error_in_times") - 1) {
			el.setAttr("enable_vcode", true);
		}
	}
	
	public void update_weixin(EventLoader el, long user_id) {
		UserWeiXinInfo weixin_info = el.getSessionAttr("weixin_info", UserWeiXinInfo.class);
		weixin_info.setUser_id(user_id);
		if (user_id != -1) {
			weixin_info.setRegistered(UserWeiXinInfo.REGISTERED_TRUE);
		}
		try {
			weixin_dao.update_user_id(weixin_info);
			weixin_dao.delete_old(weixin_info.getId(), user_id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void user_center(EventLoader el,long project_id) throws IOException, ServletException {
		FDCAgent user = el.getSessionAttr("user", FDCAgent.class);
		List<FDCProject> list = null;
		try {
			list = project_dao.getAllByFront(project_id,FDCProjectStatus.onsale.getCode());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc.project.db.failure"));
		}
		float total = 0;
		try {
			total = cash_dao.getCashTotalFlowIn(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc.project.db.failure"));
		}
		el.setAttr("total", total);
		
		int recommand = 0;
		
		try {
			recommand = kanfang_dao.getRecommandNumber(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc.project.db.failure"));
		}
		
		el.setAttr("recommand", recommand);
		el.setAttr("project_list", list);
		el.setAttr("location_list", cl.get("location"));
		el.template("/WEB-INF/template/app/"+project_id+"/fdc/usercenter/index.vm");
	}
	
	public static String IDCardValidate(String IDStr) throws ParseException {
		String errorInfo = "";// 记录错误信息
		String[] ValCodeArr = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" };
		String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2" };
		String Ai = "";
		// ================ 号码的长度 15位或18位 ================
		if (IDStr.length() != 15 && IDStr.length() != 18) {
			errorInfo = "身份证号码长度应该为15位或18位。";
			return errorInfo;
		}
		// =======================(end)========================
		
		// ================ 数字 除最后以为都为数字 ================
		if (IDStr.length() == 18) {
			Ai = IDStr.substring(0, 17);
		} else if (IDStr.length() == 15) {
			Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
		}
		if (isNumeric(Ai) == false) {
			errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。";
			return errorInfo;
		}
		// =======================(end)========================
		
		// ================ 出生年月是否有效 ================
		String strYear = Ai.substring(6, 10);// 年份
		String strMonth = Ai.substring(10, 12);// 月份
		String strDay = Ai.substring(12, 14);// 月份
		if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) {
			errorInfo = "身份证生日无效。";
			return errorInfo;
		}
		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150 || (gc.getTime().getTime() - s.parse(strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
				errorInfo = "身份证生日不在有效范围。";
				return errorInfo;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}
		if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
			errorInfo = "身份证月份无效";
			return errorInfo;
		}
		if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
			errorInfo = "身份证日期无效";
			return errorInfo;
		}
		// =====================(end)=====================
		
		// ================ 地区码时候有效 ================
		Hashtable h = GetAreaCode();
		if (h.get(Ai.substring(0, 2)) == null) {
			errorInfo = "身份证地区编码错误。";
			return errorInfo;
		}
		// ==============================================
		
		// ================ 判断最后一位的值 ================
		int TotalmulAiWi = 0;
		for (int i = 0; i < 17; i++) {
			TotalmulAiWi = TotalmulAiWi + Integer.parseInt(String.valueOf(Ai.charAt(i))) * Integer.parseInt(Wi[i]);
		}
		int modValue = TotalmulAiWi % 11;
		String strVerifyCode = ValCodeArr[modValue];
		Ai = Ai + strVerifyCode;
		
		if (IDStr.length() == 18) {
			if (Ai.equals(IDStr) == false) {
				errorInfo = "身份证无效，不是合法的身份证号码";
				return errorInfo;
			}
		} else {
			return "";
		}
		// =====================(end)=====================
		return "";
	}
	
	private static Hashtable GetAreaCode() {
		Hashtable hashtable = new Hashtable();
		hashtable.put("11", "北京");
		hashtable.put("12", "天津");
		hashtable.put("13", "河北");
		hashtable.put("14", "山西");
		hashtable.put("15", "内蒙古");
		hashtable.put("21", "辽宁");
		hashtable.put("22", "吉林");
		hashtable.put("23", "黑龙江");
		hashtable.put("31", "上海");
		hashtable.put("32", "江苏");
		hashtable.put("33", "浙江");
		hashtable.put("34", "安徽");
		hashtable.put("35", "福建");
		hashtable.put("36", "江西");
		hashtable.put("37", "山东");
		hashtable.put("41", "河南");
		hashtable.put("42", "湖北");
		hashtable.put("43", "湖南");
		hashtable.put("44", "广东");
		hashtable.put("45", "广西");
		hashtable.put("46", "海南");
		hashtable.put("50", "重庆");
		hashtable.put("51", "四川");
		hashtable.put("52", "贵州");
		hashtable.put("53", "云南");
		hashtable.put("54", "西藏");
		hashtable.put("61", "陕西");
		hashtable.put("62", "甘肃");
		hashtable.put("63", "青海");
		hashtable.put("64", "宁夏");
		hashtable.put("65", "新疆");
		hashtable.put("71", "台湾");
		hashtable.put("81", "香港");
		hashtable.put("82", "澳门");
		hashtable.put("91", "国外");
		return hashtable;
	}
	
	/**
	 * 功能：判断字符串是否为数字
	 * 
	 * @param str
	 * @return
	 */
	private static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (isNum.matches()) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 功能：判断字符串是否为日期格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isDate(String strDate) {
		Pattern pattern = Pattern
			.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
		Matcher m = pattern.matcher(strDate);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 
	 * http://jjr.weizhi.in/Home/Broker/index?waid=268&uid=142658&wz_time=1411434433&wz_token=5a6f776c3aefe3ef6b7a33bb49f78890
	 * 
	 * */
	public static void main(String[] args) throws HttpException, IOException {
		System.out.println('\u6210' + "=" + '\u529f');
		//login();
		System.out.println("============================================================");
		//recommand();
		//owner_login();http://jjr.weizhi.in/Home/Broker/center
		//register();
		///Home/Broker/center/waid/268/uid/174435/wz_time/1411433868/wz_token/95340ebc9852437f85efafc5ecee6c49
	}
	
}
